/**
 * {
 *	username:{type:'TextBox',
 *			  readOnly:false,
 *			  defaultValue:'value',
 *			  validator:['empty','username']
 *			},
 *	password:{
 *			  type:'Password',
 *			  defaultValue:'value',
 *			  validator:['empty','password']
 *			}
 * }
 */
var plugor_language = {};
plugor_language.name = {};
plugor_language.info = {};
plugor_language.message = {
	notempty:'{name}不允许为空！',
	error:'{name}格式不正确（要求：{info}）！',
	checking:'{name}验证中……',
	exist:'{name}已存在。',
	busy:'服务器忙……',
	fail:'验证失败……',
	different:'两次输入{name}不一致！'
};
var formType = {
	editor:function(options){
		//return $('<textarea class="'+options.cls+'" id="'+options.id+'" name="'+options.id+'" style="'+options.style+'">'+options.value+'</textarea>').xheditor();
		return '<textarea class="'+options.cls+'" id="'+options.id+'" name="'+options.name+'" style="'+options.style+'">'+options.value+'</textarea>';
	},
	text:function(options){//{id:'id',readonly:true,style:'width:150px',value:'test'}
		var readonly = options.readonly ? 'readOnly':'';
		return '<input class="'+options.cls+'" type="text" '+readonly+' id="'+options.id+'" name="'+options.name+'" style="'+options.style+'" value="'+options.value+'" />';
	},
	password:function(options){//{id:'id',style:'width:150px'}
		return '<input class="'+options.cls+'" type="password" id="'+options.id+'" name="'+options.name+'" style="'+options.style+'"/>';
	},
	hidden:function(options){//{id:'id',value:'test'}
		return '<input type="hidden" id="'+options.id+'" name="'+options.name+'" value="'+options.value+'"/>';
	},
	textarea:function(options){//{id:'id',style:'width:400px;height:100px;',value:'test'}
		return '<textarea class="'+options.cls+'" id="'+options.id+'" name="'+options.name+'" style="'+options.style+'">'+options.value+'</textarea>';
	},
	select:function(options){//{id:'id',style:'width:150px',value:'test',data:{key:value}}
		var select = '<select class="'+options.cls+'" id="'+options.id+'" name="'+options.name+'" style="'+options.style+'">';
		var temp;
		for(var o in options.data){
			temp = option.data[o];
			select += '<option value="'+o+'" '+(value==temp?'selected':'')+'>'+temp+'</option>';
		}
		return select+'</select>';
	},
	radio:function(options){
		
	},
	checkbox:function(options){
		
	},
	button:function(options){
		
	},
	submit:function(options){
		
	}
	
};
var validator = {
	checking:"checking",
	eq:{
		test:function(val,eqval){//相等验证
			return val == eqval;
		},
		msg:'不一致！'
	},
	exist:{
		test:function(url,id,val,_this){
			$.ajax({
				type: "POST",
				url: url+"/"+val,
				dataType: "json",
				success: function(result){
					if(result.state == 0){
						_this._tip_ok(id, '');
					}else if(result.state == 1){
						_this._tip_error(id, _this._getMessage(id, 'exist'));
					}else{
						_this._tip_error(id, _this._getMessage(id, 'busy'));
					}
				},
				error: function(){
					_this._tip_error(id, _this._getMessage(id, 'fail'));
				}
			});
			return validator.checking;
		},
		msg:''
	},
	isEmpty:{
		test:function(str){//是否为空
			return (str || "").replace( /^\s+|\s+$/g, "") === "";
		},
		msg:'不允许为空！'
	},
	decimal:{
		test:function(str){//小数
			return /^\d+([\.]?\d{1,2})?$/.test(str);
		},
		msg:'请填写正整数或小数（精确2位）！'		
	},
	number:{
		test:function(str){//数字
			return /^\d+$/.test(str);
		},
		msg:'请填写整整数！'
	},
	code:{
		test:function(str){
			return /^[A-Za-z0-9]+$/.test(str);
		},
		msg:'请填写数字或者字母！'
	},
	username:{
		test:function(str){//用户名4-16位字母、数字和下划线（_）组成，（必须以字母开头）。
			return /^[A-Za-z]\w{3,15}$/.test(str);
		},
		msg:'4-16位字母、数字和下划线（_）组成，（必须以字母开头）！'
	},
	password:{
		test:function(str){//密码长度6～16位，字母区分大小写。
			return /\S{6,16}/.test(str);
		},
		msg:'密码长度6～16位，字母区分大小写！'
	},
	realname:{
		test:function(str){
			return /^([\u4e00-\u9fa5]{2,12})|([a-zA-Z0-9]{3,20})$/.test(str);
		},
		msg:'汉字(2~12)或字母(3-20)组成！'
	},
	email:{
		test:function(str){
			return /^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}\.){1,4}[a-z]{2,4}$/.test(str);
		},
		msg:'格式错误！'
	},
	mobile:{
		test:function(str){//手机号码
			return /^1(3\d{1}|5[389])\d{8}$/.test(str);
		},
		msg:'格式错误！'
	},
	phone:{
		test:function(str){//
			return /^(\+)?([0-9]{1,3}[-\s])?([0-9]{3,4}[-\s])?([0-9]{7,8})([-\s][0-9]{1,5})?$/.test(str);
		},
		msg:'格式错误！'
	},
	address:{
		test:function(str){//
			return /(^[\u4e00-\u9fa5]*[0-9a-zA-Z]*([\u4e00-\u9fa5]|[0-9a-zA-Z])*$)/.test(str);
		},
		msg:'请输入正确的地址！'
	},
	postcode:{
		test:function(str){
			return /^[0-9]{6}$/.test(str);
		},
		msg:'请输入正确的邮编！'
	},
	url:{
		test:function(str){
			return /^([a-z]+:\/\/)?([\w-]+)\.([\w-]+)(\.[\w-]+)*(\/)?[^\s]*$/.test(str);
		},
		msg:'格式错误！eg:http://www.wocing.com'
	}
}

plugor.form = function(form,options){
//	this._required = '_required';//必填
	this._name = '_name';		//名字
	this._value = '_value';		//内容
	this._tip = '_tip';			//提示
	this._view = true;		//提示信息：true 显示在页面上；false 鼠标划过输入框才显示到页面。
	
//	this._tip_icon = '_tip_icon'; //提示图标
//	this._tip_msg = '_tip_msg'; //提示信息
//	this._right = '_right';		//正确
//	this._wrong = '_wrong';		//错误
//	this._warning = '_warning';	//警告
//	this._waiting = '_waiting';	//等待

	this._input_class = {
		def:'input',//默认的
		ok:'inputright',
		error:'inputred',
		focus:'inputgreen',
		loading:''
	};
	this._tip_class = {
		def:'tip_default',
		notice:'tip_notice',
		ok:'tip_ok',
		error:'tip_error',
		loading:'tip_loading'
	};
	
	this._form = form;
	this._options = options;
	this.init();
}

plugor.form.prototype = {
	init:function(){
		var val,text,$span,_this=this,formId = this._form.formid,formAction = this._form.action,$form = $('#'+formId),
		submit = this._form.submit,redirect = this._form.redirect,callback = this._form.callback;
		
		if(!formAction || formAction == 'null') 
			formAction = $form[0].action;
//		else
//			$form[0].action = formAction;
		plugor_language.name[formId]={};
		plugor_language.info[formId]={};
		//初始化form
		$form.submit(function(){
			if(_this._onsubmit($form)){
				switch(submit){
					case 'ajax':
						$.post(formAction,$form.serializeArray(),function(result){
							message(result.state?'ok':'error',result.message);
							if(callback){
								callback($form,result);
								return;
							}
							alert(result.html);
							if(result.html){
								$form.replaceWith(result.html);
								return;
							}
							if(redirect){
								if(top.location)
									top.location = redirect;
								else
									window.location = redirect;
								return;
							}
							if(plugor.endsWith(formAction,'add')){
								_this._reset(formId,$form);
							}else if(plugor.endsWith(formAction,'edit')){
								top.location.reload();
							}
						},'json');
						break;
					case 'submit':
						$form[0].action = formAction;
						$form[0].submit();
						break;
				}
			}
			return false;
		});
		/*
		$('.formSubmit').click(function(){
			$form[0].action = formAction+'?isGo=0'; 
			$form.submit();
		});
		$('.formSubmitGo').click(function(){
			$form[0].action = formAction;
			$form.submit();
		});
		$('.formAjaxSave,.formAjaxGo,.formAjaxList').click(function(){
			if(_this._onsubmit($form)){
				var $this = $(this);
				var isGo = $this.hasClass('formAjaxSave')?'0':$this.hasClass('formAjaxGo')?'1':'2';
//				$.post(formAction+'?isGo='+isGo,$form.serialize(),function(data){//java
				$.post(formAction+'/'+isGo,$form.serialize(),function(data){//php
					if(data.state == 0){
						alert(data.message);
					}else if(data.state == -1){
						alert(data.message);
					}else{
						if(+isGo == 0){
							window.location.href=data.data+'&message='+data.message;
						}else{
							window.location.href=data.data+'?message='+data.message;
						}
					}
				},'json');
			}
		});*/
		
		if(!this._options){//
			var options = '{';
			var $formItem = $('#'+formId).find('span');
			var size = $formItem.size();
			$formItem.each(function(i,item){
				options += $(item).attr('tp') + ( i == size-1 ? '' :',');
			});
			options += '}';
			this._options = eval('('+options+')');
		}
		//初始化form表单
		for(var k in this._options){
			val = this._options[k];
			$span = $('#'+ k + this._value);
			plugor_language.name[formId][k] = $('#'+ k +this._name).text();
			plugor_language.info[formId][k] = $('#'+ k +this._tip).html();
			
			if(val.type){
				var _formType = formType[val.type];
				if(_formType){
					$span.replaceWith(_formType({id:k,name:(val.name?val.name:k),cls:$span.attr('class'),style:$span.attr('style'),value:$span.text()}));
					if(val.type == 'editor'){
						$('#'+k).xheditor({upImgUrl:'/upload/image-editor.do?sign='+formId+'&temp='+$('#temp').val()});
					}
				}
			}
			
			_this._tip_default(k);
			if(val['validator'] && val['validator'][0] !== 'empty'){
				var $_name = $('#'+ k + this._name);
				if(!$_name[0])
					return;
				if($_name.parent()[0].tagName.toLowerCase() === 'label')
					$_name.parent().before('<span class="red">* </span>')
				else
					$_name.before('<span class="red">* </span>');
			}
			this.bindEvent(k);
		}
	},
	bindEvent:function(id){
		var _this = this;
		$('#'+ id).mouseover(function(){
			
		}).focus(function(){
			_this._tip_notice(id);
		}).blur(function(){
			_this.validator(id);
		});
	},
	validator:function(id){
		var val = $('#'+id).val();//
		var valids = this._options[id]['validator'];
		var valid;
		var is = false;//查看是否存在验证器。
		var res = false;//验证结果(ture||false)
		var msg = 'error';//抛出信息
		if(!valids){
			this._tip_default(id);
			return;
		}
		for(var i=0,j=valids.length;i<j;i++){
			valid = valids[i];
			if(valid === 'empty'){
				if(validator['isEmpty'].test(val)){
					this._tip_default(id);
					return;
				}else
					continue;
			}else{
				if(validator['isEmpty'].test(val)){
					this._tip_error(id,this._getMessage(id,'notempty'));
					return;
				}
				var valid_idx = valid.indexOf(":");
				var valid_val = null;
				if( valid_idx > -1){
					var temp = valid;
					valid = temp.substring(0,valid_idx);
					valid_val = temp.substring(valid_idx+1);
				}
				is = validator[valid].test;//获取验证器。
				msg = validator[valid].msg;//错误提示信息。
				if(is){
					if(valid === 'eq'){
						res = is(val,$('#'+valid_val).val());
						//msg = 'different';
					}else if(valid === 'exist'){
						res = false;//暂时没找为什么res等于true
						valid_idx = valid_val.indexOf("|");
						if(valid_idx > -1){
							temp = valid_val.substring(valid_idx+1);
							valid_val = valid_val.substring(0,valid_idx);
							if(val == temp){
								res = true;
							}
						}
						if(!res){
//							alert(valid_val+"-"+"-"+id+"-"+val);
							res = is(valid_val,id,val,this);
						}
					}else{
						res = valid_val ? is(val,valid_val) : is(val);
					}
					switch(res){
						case validator['checking']:
							this._tip_loading(id,this._getMessage(id,'checking'));
							break;
						case true:
							this._tip_ok(id,'');
							continue;
						case false:
							this._tip_error(id,this._getMessage(id, msg));
							break;
					}
					return;
				}
			}
		}
	},
	_getMessage:function(id,str){
		var formId = this._form.formid;
		var msg = plugor_language.message[str];
		msg = msg ? msg : str;
		return msg.replace('{name}',plugor_language.name[formId][id])
			.replace('{info}',plugor_language.info[formId][id]);
	},
	_tip_default:function(id){
		var view = '';
		if(this._view){
			view = plugor_language.info[this._form.formid][id];
		}
		$('#'+id).removeClass().addClass(this._input_class.def);
		$('#'+id+this._tip).removeClass().addClass(this._tip_class.def).html(view);
	},
	_tip_notice:function(id){
		$('#'+id).removeClass().addClass(this._input_class.focus);
		$('#'+id+this._tip).removeClass().addClass(this._tip_class.notice).html(plugor_language.info[this._form.formid][id]);
	},
	_tip_ok:function(id,str){
		$('#'+id).removeClass().addClass(this._input_class.ok);
		$('#'+id+this._tip).removeClass().addClass(this._tip_class.ok).html(str);
	},
	_tip_error:function(id,str){
		$('#'+id).removeClass().addClass(this._input_class.error);
		$('#'+id+this._tip).removeClass().addClass(this._tip_class.error).html(str);
	},
	_tip_loading:function(id,str){
		$('#'+id+this._tip).removeClass().addClass(this._tip_class.loading).html(str);
	},
	_getFormData:function($form){
		var data = {} ;
		$form.find(":input").each(function(i,n) {
			if($(n).is(":radio")||$(n).is(":checkbox")) if(!$(n).attr("checked"))return;
			data[n.name] = $(n).val();
		}) ;
		data['random'] = Math.random();
		return data;
	},
	_onsubmit:function($form){
		var val,text,$span;
		for(var k in this._options){
			this.validator(k);
		}
		if($form.find('.'+this._input_class.error).length > 0)
			return false;
		else
			return true;
	},
	_reset:function(formid,$form){
		$form[0].reset();
		$form.find('div[class^="tip_"]').removeClass().addClass(this._tip_class.def);
		var info = plugor_language.info[formid];
		for(var name in info){
			$('#'+ name + '_tip').html(info[name]);
		}
	}
}
